package com.uniapp.server.security;

import com.uniapp.server.config.jwt.JwtConfig;
import com.uniapp.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 读取JWT token将User信息设置到SpringSecurity Authentication中
 *
 * @author
 */
@Configuration
@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtConfig tokenProvider;

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        String whilePath = "/api/login";
        String whileMethod = "OPTIONS";

        if (request.getMethod().equals(whileMethod)) {
            filterChain.doFilter(request, response);
            return;
        }

        if (servletPath.equals(whilePath)) {
            log.info(request.toString());
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = getJwtTokenFromRequest(request, response);

        try {
            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
                log.info("请求的token {}", jwt);
                userService.loadUserByName(tokenProvider.getUserInfoFromToken(jwt));
            }
        } catch (Exception e) {
            log.error("Could not set user authentication in security context", e);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "认证失败");
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * get jwt token from request header
     *
     * @param
     * @return
     */
    public String getJwtTokenFromRequest(HttpServletRequest request, HttpServletResponse response) {
        String headerName = "Authorization";
        String headerStart = "Bearer ";

        String bearerToken = request.getHeader(headerName);
        if (StringUtils.hasText(bearerToken) &&
                bearerToken.startsWith(headerStart)) {
            return bearerToken.substring(headerStart.length());
        } else {
            try {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
